//
//  RAPAFNHTTPRequestTool.swift
//  TEST-HTTPRequestTool@Swift
//
//  Created by 闫萌 on 12/28/15.
//  Copyright © 2015 RendezvousAuParadis. All rights reserved.
//

import UIKit
import AFNetworking // 手动引入，因为这是两个target

enum RAPAFNHTTPRequestMethod: String {
    case GET = "GET"
    case POST = "POST"
}

typealias RAPAFNHTTPRequestCompletionHandler = (responseObject: AnyObject?, error: NSError?)->()

class RAPAFNHTTPRequestTool: AFHTTPSessionManager {
    
    // MARK: - 单例属性
    static let sharedTool: RAPAFNHTTPRequestTool = {
        let tool = RAPAFNHTTPRequestTool()
        tool.responseSerializer.acceptableContentTypes.insert("text/html")
        tool.responseSerializer.acceptableContentTypes.insert("text/plain")
        return tool
        }()
    
    ///  data task的基础方法
    ///
    ///  - parameter method:     请求方式
    ///  - parameter URLString:  url
    ///  - parameter parameters: 参数
    ///  - parameter finished:   完成回调
    func sendRequestUsingMethod(method: RAPAFNHTTPRequestMethod, URLString: String, parameters: AnyObject?, finished: RAPAFNHTTPRequestCompletionHandler) {
        
        let success = { (task: NSURLSessionDataTask!, responseObject: AnyObject!) -> Void in
            finished(responseObject: responseObject, error: nil)
        }
        
        let failure = { (task: NSURLSessionDataTask!, error: NSError!) -> Void in
            finished(responseObject: nil, error: error)
        }
        
        if method == .GET {
            GET(URLString, parameters: parameters, success: success, failure: failure)
        } else if method == .POST {
            POST(URLString, parameters: parameters, success: success, failure: failure)
            
        }
    }
    
    
    func sendRequestWithUploadData(data: NSData, URLString: String, parameters: AnyObject?, finished: RAPAFNHTTPRequestCompletionHandler) {
        
        let success = { (task: NSURLSessionDataTask!, responseObject: AnyObject!) -> Void in
            finished(responseObject: responseObject, error: nil)
        }
        
        let failure = { (task: NSURLSessionDataTask!, error: NSError!) -> Void in
            finished(responseObject: nil, error: error)
        }
        
        POST(URLString, parameters: parameters, constructingBodyWithBlock: { (formData) -> Void in
            // 恶心，不提示
            formData.appendPartWithFileData(data, name: "pic", fileName: "any", mimeType: "application/octet-stream")
            
        }, success: success, failure: failure)

    }
}

// MARK: - weibo API调用便利方法
// 注意，这个扩展专供 weibo项目使用
extension RAPAFNHTTPRequestTool {
    
    ///  根据 code 请求 access token
    ///
    ///  - parameter code:     authorization code
    ///  - parameter finished: 完成回调
    func fetchAccessTokenByCode(code: String, finished: RAPAFNHTTPRequestCompletionHandler) {
        
        // 开始请求访问token
        let param = [
            "client_id" : kRAPAppKey,
            "client_secret" : kRAPAppSecret,
            "grant_type" : "authorization_code",
            "code" : code,
            "redirect_uri" : kRAPRedirectURI
        ]
        
        sendRequestUsingMethod(.POST, URLString: kAPI_oauth2_access_token, parameters: param, finished: { (responseObject, error) -> () in
            finished(responseObject: responseObject, error: error)
        })
    }
    
    ///  根据 access token 请求用户数据
    ///
    ///  - parameter model:    用户账户信息模型
    ///  - parameter finished: 完成回调
    func fetchUserInfo(model: RAPAccountModel, finished: RAPAFNHTTPRequestCompletionHandler) {
        // 继续请求用户数据
        let params = [
            "access_token" : model.access_token!,
            "uid" : model.uid!
        ]
        
        sendRequestUsingMethod(RAPAFNHTTPRequestMethod.GET, URLString: kAPI_users_show, parameters: params, finished: { (responseObject, error) -> () in
            finished(responseObject: responseObject, error: error)
        })
    }
    
    ///  根据access token 请求最新微博数据
    ///
    ///  - parameter model:    用户账户信息模型
    ///  - parameter finished: 完成回调
    func fetchStatuses(max_id max_id: Int64 = 0, since_id: Int64 = 0, finished: RAPAFNHTTPRequestCompletionHandler) {
        let params = [
            "access_token" : RAPAccountViewModel.sharedViewModel.accessToken()!,
            "max_id" : "\(max_id)",
            "since_id" : "\(since_id)"
        ]

        sendRequestUsingMethod(RAPAFNHTTPRequestMethod.GET, URLString: kAPI_statuses_friends_timeline, parameters: params, finished: { (responseObject, error) -> () in
            finished(responseObject: responseObject, error: error)
//            print(responseObject)
        })
    }
    
    ///  发送一条（带单张配图）的微博
    ///
    ///  - parameter status:   微博字符串
    ///  - parameter image:    可能的图片
    ///  - parameter finished: 回调
    func sendStatus(status: String!, image: UIImage? = nil, finished: RAPAFNHTTPRequestCompletionHandler) {
        let params = [
            "access_token" : RAPAccountViewModel.sharedViewModel.accessToken()!,
            "status" : status
        ]
        
        if let opImage = image { // 如果image有值，就是一个带图片的上传方法
            sendRequestWithUploadData(UIImagePNGRepresentation(opImage)!, URLString: kAPI_2_statuses_upload, parameters: params) { (responseObject, error) -> () in
                finished(responseObject: responseObject, error: error)
            }
        } else { // 否则是一个普通的上传方法
            sendRequestUsingMethod(RAPAFNHTTPRequestMethod.POST, URLString: kAPI_statuses_update, parameters: params, finished: { (responseObject, error) -> () in
                finished(responseObject: responseObject, error: error)
            })
            
        }
        
    }
    
}
